#! /usr/bin/perl -w
#---------------------------------------------------------------------------------
#  make_holiday.pl is part of the BART dashboard widget.  (c) 2005 Bret Victor
#                                                         (c) 2010 Bradley Froehle
#  This software is licensed under the terms of the open source MIT license.
#---------------------------------------------------------------------------------
#
#  perl make_holiday.pl > Holiday.js
#
#  Downloads the holiday service levels from bart.gov and generates a JavaScript
#  holiday list on stdout.  This becomes the Holiday.js file.
# 
# (Requires LWP::Simple & XML::Simple.  Found in MacPorts p5-libwww-perl & p5-xml-simple.)

use strict;
use LWP::Simple;
use XML::Simple;

#-----------------------------------------------------------------
#  Main code

print STDERR "Generating holidays...\n";

print getHeader();

my $content = get("http://api.bart.gov/api/sched.aspx?cmd=holiday&key=MW9S-E7SL-26DU-VV8V");
my $xml = new XML::Simple;
my $data = $xml->XMLin($content, KeyAttr => []);

print parseXml($data);
print getFooter();
exit();

#-----------------------------------------------------------------
#  Bart XML input parsing

sub parseXml {
    my ($data) = @_;
    my $out = "\n    servicelevel = {}\n";

    foreach my $holiday (@{$data->{holidays}->{holiday}})
    {
        my $date = $holiday->{date};
        my $service = lc($holiday->{schedule_type});
        # my $name = $holiday->{name};
        $out .= "    servicelevel['$date'] = '$service'\n";
    }
    
    return $out;
}

#-----------------------------------------------------------------
#  JavaScript output generation

sub getHeader {
    my $now = localtime;
    return <<_EOT_;
//-----------------------------------------------------------------------------
//  Holiday.js is part of the BART dashboard widget.  (c) 2005 Bret Victor
//  This software is licensed under the terms of the open source MIT license.
//-----------------------------------------------------------------------------
//
//  Service Levels -- http://www.bart.gov/guide/holidays.aspx
//
//  Automatically generated by make_holiday.pl on $now.
//

function Holiday () {
_EOT_
}

sub getFooter {
    return <<_EOT_;
    
    Holiday.getServiceLevel = function(date) {
        var date_string = date.toMMDDYYYYString()
        var day_of_week = date.getDay()
        
        return servicelevel[date_string] ||
            ( (day_of_week == 0)        ? 'sunday'
            : (day_of_week == 6)        ? 'saturday'
            :                             'weekday')
    }
}

// Open the package.
Holiday();

_EOT_
}
